package com.zust513.service.impl;

import com.zust513.entity.Order;
import com.zust513.mapper.OrderMapper;
import com.zust513.mapper.rrr.CourierMapperR;
import com.zust513.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CourierMapperR courierMapper;

    @Override
    public int getTotalDeliveryOrdersByCourierId(Integer courierId) {
        return orderMapper.getTotalDeliveryOrdersByCourierId(courierId);
    }

    @Override
    public int getTodayOrdersByCourierId(Integer courierId) {
        String today = LocalDate.now().format(DateTimeFormatter.ISO_DATE);
        return orderMapper.getTodayOrdersByCourierId(courierId, today);
    }

    @Override
    public int getWeekOrdersByCourierId(Integer courierId) {
        LocalDate today = LocalDate.now();
        LocalDate weekAgo = today.minusWeeks(1);
        return orderMapper.getOrdersByDateRange(courierId, weekAgo.toString(), today.toString());
    }

    @Override
    public int getMonthOrdersByCourierId(Integer courierId) {
        LocalDate today = LocalDate.now();
        LocalDate monthAgo = today.minusMonths(1);
        return orderMapper.getOrdersByDateRange(courierId, monthAgo.toString(), today.toString());
    }

//    @Override
//    @Transactional
//    public void acceptOrder(Integer orderId, Integer courierId) {
//        // 1. 更新订单状态为已接单，并分配配送员
//        orderMapper.acceptOrder(orderId, courierId);
//
//        // 2. 更新配送员当前状态为忙碌
//        // courierMapper.updateCourierStatus(courierId, "busy");
//    }

//    @Override
//    public void updateOrderStatus(Integer orderId, String status) {
//        orderMapper.updateOrderStatus(orderId, status);
//    }

    @Override
    public List<Order> getDeliveryRecordsByCourierId(Integer courierId) {
        return orderMapper.getDeliveryRecordsByCourierId(courierId);
    }

    @Override
    public List<Order> getOrdersByCourierId(Integer courierId) {
        return orderMapper.getOrdersByCourierId(courierId);
    }

    @Override
    @Transactional
    public void transferEarningsToCourier(Integer orderId) {
        // 1. 获取订单信息
        Order order = orderMapper.getOrderById(orderId);

        // 2. 获取配送费用
        BigDecimal deliveryFee = order.getDeliveryFee();

        // 3. 更新配送员余额
        courierMapper.updateCourierBalance(order.getCourierId(), deliveryFee);

        // 4. 记录收益转移历史
        // 注：需要添加 EarningsHistory 实体和 Mapper
        // earningsHistoryMapper.recordEarnings(orderId, order.getCourierId(), deliveryFee);
    }

    @Override
    public List<Map<String, Object>> getEarningsByCourierId(Integer courierId) {
        return orderMapper.getEarningsByCourierId(courierId);
    }

    @Override
    public List<Order> getAllOrdersByCourierId(Integer courierId) {
        return orderMapper.getAllOrdersByCourierId(courierId);
    }

    @Override
    public List<Order> getAllPendingOrders() {
        return orderMapper.getAllPendingOrders();
    }

    @Override
    public List<Order> getPendingOrdersByCourierId(Integer courierId) {
        return orderMapper.getPendingOrdersByCourierId(courierId);
    }

    // 获取配送员当前需配送的订单数量
    public int getPendingOrderCountByCourierId(Integer courierId) {
        return orderMapper.getPendingOrderCountByCourierId(courierId);
    }

    @Override
    @Transactional
    public int acceptOrder(Integer orderId, Integer courierId) {
        // 检查配送员当前需配送的订单数量
        int pendingOrderCount = getPendingOrderCountByCourierId(courierId);
        if (pendingOrderCount >= 5) {
            throw new RuntimeException("配送员当前订单数量已达到上限，无法接单");
        }
        // 1. 更新配送员当前状态
        if (pendingOrderCount > 0) {
            courierMapper.updateCourierStatus(courierId, "busy");
            System.out.println("Updating courier status to busy for courier ID: " + courierId);
        } else {
            courierMapper.updateCourierStatus(courierId, "idle");
            System.out.println("Updating courier status to idle for courier ID: " + courierId);
        }
        // 2. 更新订单状态为已接单，并分配配送员
        return orderMapper.acceptOrder(orderId, courierId);
    }

    @Override
    public void updateOrderStatus(Integer orderId, String status) {
        orderMapper.updateOrderStatus(orderId, status);
        // 假设订单完成后，重新计算配送员状态
        Integer courierId = orderMapper.getCourierIdByOrderId(orderId);
        if (courierId != null) {
            int pendingOrderCount = getPendingOrderCountByCourierId(courierId);
            // 需配送订单数量为 0，将配送员状态设置为空闲
            if (pendingOrderCount == 0) {
                courierMapper.updateCourierStatus(courierId, "idle");
                System.out.println("Updating courier status to idle for courier ID: " + courierId);
            } else {
                courierMapper.updateCourierStatus(courierId, "busy");
                System.out.println("Updating courier status to busy for courier ID: " + courierId);
            }
        }
    }

    @Override
    public int confirmDelivery(Integer orderId) {
        // 获取当前时间
        LocalDateTime completedAt = LocalDateTime.now();

        // 调用 Mapper 更新订单状态并设置 completed_at
        int result = orderMapper.confirmDelivery(orderId, completedAt);

        // 检查受影响行数是否为 1，表示更新成功
        if (result == 0) {
            throw new RuntimeException("更新订单状态失败");
        }
        Integer courierId = orderMapper.getCourierIdByOrderId(orderId);
        if (courierId != null) {
            // 新增：每完成一个订单，配送员余额增加 2 元
            BigDecimal amount = new BigDecimal("2");
            courierMapper.updateAccountBalance(courierId, amount);

            int pendingOrderCount = getPendingOrderCountByCourierId(courierId);
            // 确认送达后需配送订单数量为 0，将配送员状态设置为空闲
            if (pendingOrderCount == 0) {
                courierMapper.updateCourierStatus(courierId, "idle");
                System.out.println("Updating courier status to idle for courier ID: " + courierId);
            } else {
                courierMapper.updateCourierStatus(courierId, "busy");
                System.out.println("Updating courier status to busy for courier ID: " + courierId);
            }
        }
        return result;
    }

    //删除订单
    @Override
    public void withdrawAndDeleteOrders(Integer courierId, int amount) {
        if (amount <= 0 || amount % 2 != 0) {
            throw new IllegalArgumentException("提现金额必须是正数且为 2 的倍数");
        }

        int ordersToDeleteCount = amount / 2;

        List<Map<String, Object>> completedOrders = orderMapper.getCompletedOrdersByCourierId(courierId);

        if (completedOrders == null || completedOrders.size() < ordersToDeleteCount) {
            throw new IllegalArgumentException("订单不足，无法完成提现");
        }

        List<Integer> orderIdsToDelete = completedOrders.stream()
                .limit(ordersToDeleteCount)
                .map(order -> (Integer) order.get("orderId"))
                .toList();

        orderMapper.deleteOrdersByIds(orderIdsToDelete);
    }

    @Override
    public Integer getTotalOrdersCount() {
        return orderMapper.getTotalOrdersCount();
    }

    @Override
    public List<Map<String, Object>> getRecentOrders(int limit) {
        return orderMapper.getRecentOrders(limit);
    }

}
